/** 获取基金列表 **/
"use strict";

const fs = require("fs");
const axios = require("axios");
const nodeUtils = require("../../../utils/nodeUtils");
const BrowserFundCode = require("../puppeteer/fundcode");

const Controller = require("egg").Controller;

class ListController extends Controller {
  // 从天天基金网，下载基金列表js
  async downloadFundCode() {
    const ctx = this.ctx;
    let response = await axios({
      method: "get",
      url: `http://fund.eastmoney.com/js/fundcode_search.js`,
      responseType: "stream",
    });
    nodeUtils.mkdirsSync("app/public/fund/");
    response.data.pipe(
      fs.createWriteStream(`app/public/fund/fundcode_list.js`)
    );

    const browserFundCode = new BrowserFundCode();
    browserFundCode.getFundCodeAllToMysql();

    ctx.status = 200;
    ctx.body = "已更新全部基金代码";
  }
  // 将下载的基金列表，同步到数据库
  async postFundCodeToSql() {
    const ctx = this.ctx;
    const { fundCodeArray } = ctx.request.body;

    const fundArray = [];

    for (let itemFund of fundCodeArray) {
      fundArray.push({
        fund_code: itemFund.code,
        fund_name: itemFund.name,
        fund_type: itemFund.type,
      });
    }

    // 不设条件删除（清空表）
    await ctx.model.FundDefaultList.destroy({
      where: {},
      truncate: true,
    });
    // 数据库名，以database为准，去掉s
    ctx.body = await ctx.model.FundDefaultList.bulkCreate(fundArray, {
      updateOnDuplicate: ["fund_code", "fund_name", "fund_type"],
    });
  }
}

module.exports = ListController;
